from datetime import datetime
from app import db
from sqlalchemy.orm import relationship

class UserBehavior(db.Model):
    __tablename__ = 'tb_user_behavior'
    __table_args__ = {'extend_existing': True}
    
    behavior_id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='行为ID(主键)')
    user_id = db.Column(db.BigInteger, db.ForeignKey('tb_user.user_id', ondelete='SET NULL'), comment='用户ID')
    session_id = db.Column(db.String(100), comment='会话ID')
    action_type = db.Column(db.String(50), nullable=False, comment='行为类型(view/search/click/buy等)')
    object_type = db.Column(db.String(50), comment='对象类型(box/market/product等)')
    object_id = db.Column(db.BigInteger, comment='对象ID')
    url = db.Column(db.String(255), comment='页面URL')
    query = db.Column(db.String(255), comment='搜索查询')
    user_agent = db.Column(db.String(255), comment='用户代理')
    ip_address = db.Column(db.String(50), comment='IP地址')
    create_time = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
    
    # 与用户表建立关系 - 使用back_populates而不是backref
    user = relationship('User', back_populates='behaviors', foreign_keys=[user_id])

    def __init__(self, user_id=None, action_type=None, object_type=None, object_id=None, 
                 url=None, query=None, user_agent=None, ip_address=None, session_id=None):
        self.user_id = user_id
        self.action_type = action_type
        self.object_type = object_type
        self.object_id = object_id
        self.url = url
        self.query = query
        self.user_agent = user_agent
        self.ip_address = ip_address
        self.session_id = session_id

    def __repr__(self):
        return f'<UserBehavior {self.behavior_id}>'

    # 定义行为类型常量
    TYPE_PAGE_VIEW = 'page_view'      # 页面浏览
    TYPE_VIEW_BOX = 'view_box'        # 查看商品
    TYPE_VIEW_MARKET = 'view_market'  # 查看超市
    TYPE_VIEW_ORDER = 'view_order'    # 查看订单
    TYPE_ADD_CART = 'add_to_cart'     # 加入购物车
    TYPE_FORM_SUBMIT = 'form_submit'  # 表单提交
    TYPE_SEARCH = 'search'            # 搜索
    TYPE_CHAT = 'chat'                # 聊天
